package pre.bookcloud.java21.qoder.historysign02;

import java.awt.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;
import javax.swing.*;

/** History Sign-in UI Interface 查看历史签到UI界面 */
public class HistorySignUI extends JPanel {

  private JComboBox<String> dateComboBox;
  private JLabel titleLabel;
  private JPanel signedStudentsPanel;
  private JPanel unsignedStudentsPanel;
  private JLabel statisticsLabel;

  private static final Color SIGNED_BACKGROUND = new Color(220, 255, 220);
  private static final Color UNSIGNED_BACKGROUND = new Color(255, 220, 220);
  private static final Color SIGNED_TEXT = new Color(0, 128, 0);
  private static final Color UNSIGNED_TEXT = new Color(255, 0, 0);

  public HistorySignUI() {
    initializeComponents();
    setupLayout();
    loadData();
  }

  /** Initialize UI components 初始化UI组件 */
  private void initializeComponents() {
    setLayout(new BorderLayout());
    setBackground(Color.WHITE);

    // Date selection combo box
    dateComboBox = new JComboBox<>();
    dateComboBox.setFont(new Font("微软雅黑", Font.PLAIN, 12));

    // Populate date combo box with recent dates
    LocalDate today = LocalDate.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    for (int i = 0; i < 30; i++) {
      LocalDate date = today.minusDays(i);
      dateComboBox.addItem(date.format(formatter));
    }

    // Title label
    titleLabel = new JLabel("", JLabel.CENTER);
    titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 18));
    titleLabel.setForeground(new Color(51, 102, 255));

    // Panels for signed and unsigned students
    signedStudentsPanel = new JPanel();
    signedStudentsPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));
    signedStudentsPanel.setBackground(SIGNED_BACKGROUND);
    signedStudentsPanel.setBorder(
        BorderFactory.createTitledBorder(
            BorderFactory.createLineBorder(SIGNED_TEXT, 1),
            "已签到学生:",
            0,
            0,
            new Font("微软雅黑", Font.BOLD, 12),
            SIGNED_TEXT));

    unsignedStudentsPanel = new JPanel();
    unsignedStudentsPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 5));
    unsignedStudentsPanel.setBackground(UNSIGNED_BACKGROUND);
    unsignedStudentsPanel.setBorder(
        BorderFactory.createTitledBorder(
            BorderFactory.createLineBorder(UNSIGNED_TEXT, 1),
            "未签到学生:",
            0,
            0,
            new Font("微软雅黑", Font.BOLD, 12),
            UNSIGNED_TEXT));

    // Statistics label
    statisticsLabel = new JLabel("", JLabel.CENTER);
    statisticsLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
    statisticsLabel.setForeground(new Color(255, 102, 0));

    // Add ActionListener after all components are initialized
    dateComboBox.addActionListener(e -> loadDataForSelectedDate());
  }

  /** Setup the layout 设置布局 */
  private void setupLayout() {
    // Top panel with date selection and title
    JPanel topPanel = new JPanel(new BorderLayout());
    topPanel.setBackground(Color.WHITE);
    topPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 10, 15));

    // Date selection panel
    JPanel datePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
    datePanel.setBackground(Color.WHITE);
    JLabel dateLabel = new JLabel("选择日期: ");
    dateLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
    datePanel.add(dateLabel);
    datePanel.add(dateComboBox);

    topPanel.add(datePanel, BorderLayout.NORTH);
    topPanel.add(titleLabel, BorderLayout.CENTER);

    // Center panel with student lists
    JPanel centerPanel = new JPanel(new BorderLayout(0, 10));
    centerPanel.setBackground(Color.WHITE);
    centerPanel.setBorder(BorderFactory.createEmptyBorder(10, 15, 10, 15));

    // Signed students scroll pane
    JScrollPane signedScrollPane = new JScrollPane(signedStudentsPanel);
    signedScrollPane.setPreferredSize(new Dimension(0, 120));
    signedScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    signedScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

    // Unsigned students scroll pane
    JScrollPane unsignedScrollPane = new JScrollPane(unsignedStudentsPanel);
    unsignedScrollPane.setPreferredSize(new Dimension(0, 200));
    unsignedScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    unsignedScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

    centerPanel.add(signedScrollPane, BorderLayout.NORTH);
    centerPanel.add(unsignedScrollPane, BorderLayout.CENTER);

    // Bottom panel with statistics
    JPanel bottomPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
    bottomPanel.setBackground(Color.WHITE);
    bottomPanel.setBorder(BorderFactory.createEmptyBorder(10, 15, 15, 15));
    bottomPanel.add(statisticsLabel);

    // Add all panels to main panel
    add(topPanel, BorderLayout.NORTH);
    add(centerPanel, BorderLayout.CENTER);
    add(bottomPanel, BorderLayout.SOUTH);
  }

  /** Load data for the initially selected date 加载初始选中日期的数据 */
  private void loadData() {
    loadDataForSelectedDate();
  }

  /** Load data for the selected date 加载选中日期的数据 */
  private void loadDataForSelectedDate() {
    String selectedDate = (String) dateComboBox.getSelectedItem();
    if (selectedDate == null || titleLabel == null) return;

    // Update title
    String formattedDate = selectedDate.replaceFirst("-", "年").replaceFirst("-", "月");
    titleLabel.setText(formattedDate + "日签到情况");

    // Get student data (for demo purposes, we'll use today's data)
    List<Student> allStudents = DataUtil.getTodaySignData();

    // Separate signed and unsigned students
    List<Student> signedStudents =
        allStudents.stream().filter(s -> s.getStatus() == 1).collect(Collectors.toList());

    List<Student> unsignedStudents =
        allStudents.stream().filter(s -> s.getStatus() == 0).collect(Collectors.toList());

    // Update signed students panel
    updateStudentPanel(signedStudentsPanel, signedStudents, SIGNED_TEXT);

    // Update unsigned students panel
    updateStudentPanel(unsignedStudentsPanel, unsignedStudents, UNSIGNED_TEXT);

    // Update statistics
    updateStatistics(allStudents.size(), signedStudents.size(), unsignedStudents.size());
  }

  /** Update student panel with student names 更新学生面板显示学生姓名 */
  private void updateStudentPanel(JPanel panel, List<Student> students, Color textColor) {
    panel.removeAll();

    for (Student student : students) {
      JLabel studentLabel = new JLabel(student.getName());
      studentLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
      studentLabel.setForeground(textColor);
      studentLabel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
      panel.add(studentLabel);
    }

    panel.revalidate();
    panel.repaint();
  }

  /** Update statistics display 更新统计信息显示 */
  private void updateStatistics(int total, int signed, int unsigned) {
    double percentage = total > 0 ? (double) signed / total * 100 : 0;
    String statisticsText =
        String.format("当日记录: 共%d人，已签到%d人，未签到%d人，签到率%.1f%%", total, signed, unsigned, percentage);
    statisticsLabel.setText(statisticsText);
  }
}
